<?php
namespace app\service;

use Swoole\Http\Request as SwooleRequest;


class Request
{

    /**
     * @var SwooleRequest
     */
    protected $swooleRequest;

    /**
     * @var array|null
     */
    protected $_postJsonData = null;

    public function __construct(SwooleRequest  $request)
    {
        $this->swooleRequest = $request;
    }

    /**
     * getSwooleRequest
     * @return SwooleRequest
     */
    public function getSwooleRequest()
    {
        return $this->swooleRequest;
    }

    /**
     * rawContent
     * @return false|string
     */
    public function rawContent()
    {
        return $this->swooleRequest->rawContent();
    }

    /**
     * post
     * @param null $key
     * @param null $defaultValue
     * @return mixed|null
     */
    public function get($key=null,$defaultValue=null)
    {
        return is_null($key)?$this->swooleRequest->get:($this->swooleRequest->get[$key]??$defaultValue);
    }

    /**
     * post
     * @param null $key
     * @param null $defaultValue
     * @return mixed|null
     */
    public function post($key=null,$defaultValue=null)
    {
        return is_null($key)?$this->swooleRequest->post:($this->swooleRequest->post[$key]??$defaultValue);
    }


    /**
     * header
     * @param null $key
     * @param null $defaultValue
     * @return mixed|null
     */
    public function header($key=null,$defaultValue=null)
    {
        return is_null($key)?$this->swooleRequest->header:($this->swooleRequest->header[$key]??$defaultValue);
    }

    /**
     * server
     * @param null $key
     * @param null $defaultValue
     * @return mixed|null
     */
    public function server($key=null,$defaultValue=null)
    {
        return is_null($key)?$this->swooleRequest->server:($this->swooleRequest->server[$key]??$defaultValue);
    }

    /**
     * postJsonData
     * @param null $key
     * @param null $defaultValue
     * @return array|mixed
     */
    public function postJsonData($key=null,$defaultValue=null)
    {
        if(is_null($this->_postJsonData)){
            $this->_postJsonData = json_decode($this->swooleRequest->rawContent(),1);
        }
        return is_null($key)?$this->_postJsonData:($this->_postJsonData[$key]??$defaultValue);
    }


    /**
     * cookie
     * @param null $key
     * @param null $defaultValue
     * @return mixed|null
     */
    public function cookie($key=null,$defaultValue=null)
    {
        return is_null($key)?$this->swooleRequest->cookie:($this->swooleRequest->cookie[$key]??$defaultValue);
    }

    /**
     * isGet
     * @return bool
     */
    public function isGet()
    {
        return $this->swooleRequest->server['request_method'] == 'GET';
    }

    /**
     * isPost
     * @return bool
     */
    public function isPost()
    {
        return $this->swooleRequest->server['request_method'] == 'POST';
    }

}